package com.haoze.nurseapp.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.DateUtil;
import com.haoze.common.utils.UUIDUtil;
import com.haoze.nurseapp.dao.MealListMapper;
import com.haoze.nurseapp.dto.CirculationLogsDTO;
import com.haoze.nurseapp.dto.MealListMainDTO;
import com.haoze.nurseapp.enumeration.VarCodeEnum;
import com.haoze.nurseapp.model.WardLogMenuEntity;
import com.haoze.nurseapp.service.MealListService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: lufq
 * @CreateTime: 2020-11-12
 */
@Service
public class MealListServiceImpl implements MealListService {
    @Autowired
    private MealListMapper mealListMapper;

    public Result query(int pageNum, int pageSize, String wardId){
        String dateTime = DateUtil.dateToString(new Date(),"yyyy-MM-dd");
        String wholeInpatNum = mealListMapper.queryPatientInfoByWardDeptId(wardId);
        PageHelper.startPage(pageNum,pageSize);
        List<Map<String, String>> mealList = mealListMapper.queryMealList(wardId, dateTime,wholeInpatNum);
        if(CollectionUtils.isNotEmpty(mealList)){
            //获取所有的住院号
            List<String> inpatNums = mealList.stream().map(x->x.get("inpatNum")).collect(Collectors.toList());
            List<Map<String, String>> illnessList = mealListMapper.queryIllnessByInpatNum(inpatNums, dateTime);
            //定义集合
            List<String> nursingGradeList = Arrays.asList(VarCodeEnum.IJHL.getVarCode(), VarCodeEnum.IJHLEK.getVarCode(), VarCodeEnum.IIJHL.getVarCode(),
                                              VarCodeEnum.IIIJHLEK.getVarCode(), VarCodeEnum.IIIJHL.getVarCode(), VarCodeEnum.IIIJHLEK.getVarCode(),
                                              VarCodeEnum.YJHL.getVarCode(), VarCodeEnum.EJHL.getVarCode(), VarCodeEnum.SJHL.getVarCode(),
                                              VarCodeEnum.TJHL.getVarCode(), VarCodeEnum.TJHLEK.getVarCode(), VarCodeEnum.JHBFYJHL.getVarCode(),
                                              VarCodeEnum.JHBFEJHL.getVarCode(), VarCodeEnum.JHBFTJHL.getVarCode());
            List<Map<String, String>> nursingGradeLists = mealListMapper.queryNursingGradeByInpatNum(inpatNums, dateTime,nursingGradeList);
            System.out.println(nursingGradeLists);
            mealList.stream().forEach(x->{
                String inpatNum = x.get("inpatNum");
                Map<String, String> filterillness = illnessList.stream().filter(s -> inpatNum.equals(s.get("inpatNum"))).findFirst().orElse(null);
                if(filterillness!=null){
                    x.put("disdaseState",filterillness.get("ordersItem"));
                }else{
                    x.put("disdaseState", "普通");//病情
                }
            });
            mealList.stream().forEach(x->{
                String inpatNum = x.get("inpatNum");
                Map<String, String> filterNursingGrade = nursingGradeLists.stream().filter(s -> inpatNum.equals(s.get("inpatNum"))).findFirst().orElse(null);
                if(filterNursingGrade!=null){
                    //监护病房特级护理，特级护理，特级护理（儿科）
                    //Ⅰ级护理，Ⅰ级护理（儿科），一级护理 监护病房一级护理
                    //ⅠⅠ级护理，ⅠⅠ级护理（儿科），二级护理 监护病房二级护理
                    //ⅠⅠⅠ级护理，ⅠⅠⅠ级护理（儿科），三级护理
                    if(VarCodeEnum.TJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.TJHLEK.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.JHBFTJHL.getVarCode().equals(filterNursingGrade.get("varCode"))){
                        x.put("nursingGrade",VarCodeEnum.TJHL.getName());
                    }else if(VarCodeEnum.IJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.IJHLEK.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.YJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.JHBFYJHL.getVarCode().equals(filterNursingGrade.get("varCode"))){
                        x.put("nursingGrade",VarCodeEnum.YJHL.getName());
                    }else if(VarCodeEnum.IIJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.IIJHLEK.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.EJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.JHBFEJHL.getVarCode().equals(filterNursingGrade.get("varCode"))){
                        x.put("nursingGrade",VarCodeEnum.EJHL.getName());
                    }else if(VarCodeEnum.IIIJHL.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.IIIJHLEK.getVarCode().equals(filterNursingGrade.get("varCode")) || VarCodeEnum.SJHL.getVarCode().equals(filterNursingGrade.get("varCode"))){
                        x.put("nursingGrade",VarCodeEnum.SJHL.getName());
                    }
                    if(StringUtils.isNotBlank(x.get("nursingGrade")) && x.get("nursingGrade").length()>=2){
                        x.put("nursingGrade",x.get("nursingGrade").substring(0,2));
                    }
                }else{
                    x.put("nursingGrade", "");
                }
            });
        }
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(mealList);

        return ResultGenerator.genOkResult(pageInfo);
    }

    public Result wardLogMenu(int pageNum, int pageSize,String wardId,String search){
        String dateTime = DateUtil.dateToString(new Date(),"yyyy-MM-dd");
        String wholeInpatNum = mealListMapper.queryPatientInfoByWardDeptId(wardId);
        PageHelper.startPage(pageNum,pageSize);
        List<Map<String, String>> menuList = mealListMapper.queryWardLogMenu(wardId, dateTime,search,wholeInpatNum);
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(menuList);
        return ResultGenerator.genOkResult(pageInfo);
    }

    public Result getInpatNumByMenu(String wardId,String orderItemIds){
        String dateTime = DateUtil.dateToString(new Date(),"yyyy-MM-dd");
        List<MealListMainDTO> inpatNumList=null;
        List<MealListMainDTO> lastList=new ArrayList<>();
        String wholeInpatNum = mealListMapper.queryPatientInfoByWardDeptId(wardId);
        if(StringUtils.isNotBlank(orderItemIds)){
            String[] orderItems = orderItemIds.split(",");
            List<Map<String,String>> condition = new ArrayList<>();
            for(int i=0;i<orderItems.length;i++){
                Map<String,String> map = new HashMap<>();
                String x = orderItems[i];
                String[] orderItemAndFreq = x.split("-");
                if(orderItemAndFreq.length==2){
                    map.put("orderItemId",orderItemAndFreq[0]);
                    map.put("freq",orderItemAndFreq[1]);
                }else{
                    map.put("orderItemId",orderItemAndFreq[0]);
                    map.put("freq",null);
                }
                condition.add(map);
            }
            inpatNumList = mealListMapper.getInpatNumByOrderItemId(wardId,condition,dateTime,wholeInpatNum);
            for(Map<String,String> map:condition){
                for(MealListMainDTO mealListMainDTO:inpatNumList){
                    if(map.get("orderItemId").equals(mealListMainDTO.getOrderItemId()) && map.get("freq")==null && mealListMainDTO.getFreq()==null){
                        lastList.add(mealListMainDTO);
                        break;
                    }else if(map.get("orderItemId").equals(mealListMainDTO.getOrderItemId()) && StringUtils.isNotBlank(map.get("freq")) && map.get("freq").equals(mealListMainDTO.getFreq())){
                        lastList.add(mealListMainDTO);
                        break;
                    }
                }
            }
        }
        return ResultGenerator.genOkResult(lastList);
    }

    public Result insertWardLogMenu(List<WardLogMenuEntity> wardLogMenuEntityList){
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        if(CollectionUtils.isNotEmpty(wardLogMenuEntityList)){
            mealListMapper.deleteWardLogMenu(userId,wardLogMenuEntityList.get(0).getWardDeptId());
            for(WardLogMenuEntity wardLogMenuEntity:wardLogMenuEntityList){
                wardLogMenuEntity.setMenuId(UUIDUtil.randomString());
                wardLogMenuEntity.initAdd();
                wardLogMenuEntity.setUserId(userId);
            }
            mealListMapper.insertWardLogMenu(wardLogMenuEntityList);
        }
        return ResultGenerator.genOkResult();
    }

    public Result getWardLogMenuByNuserId(String wardId){
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        List<WardLogMenuEntity> list = mealListMapper.getWardLogMenuByNurseId(userId, wardId);
        return ResultGenerator.genOkResult(list);
    }
}
